import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
import { init } from "echarts";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.upperFirst(
      _.camelCase(
        name
          .split("/")
          .pop()
          .replace(/\.\w+$/, "")
      )
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false, //验证所有元素是否全部加载完成
      me: this,
      watchs: [],
      //模型
      models: {
        //模型
        workNotice: {
          ...typeClassName["workNotice"],
        },
        masterPlan: {
          ...typeClassName["masterPlan"],
        },
        tank: {
          ...typeClassName["tank"],
        },
      },
      parentId: "",
      productOptions: [],
      feedWorkCenterId: null,
      dataSet: {
        //数据集
        rightTableData: [],
        leftTableData: [],
        rightFormData: {},
        leftTableIds: [],
        feedIds: [],
        feedTableData: [],
        feedTableBindData: [],
        feedTableCurrent: {},
        feedTableSelection: [],
        feedCurrentIndex: null,
      },
      onlyRead: false,
      leftFilter: {},
      rightFilter: {},
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {
    detailAttrs() {
      return {
        ...this.attrs,
        columns: this.attrs.columns.map((item) => {
          item.config["disabled"] = this.onlyRead;
          return item;
        }),
      };
    },
    attrs() {
      return {
        labelWidth: 100,
        labelPosition: "right",
        cols: 3,
        columns: [
          {
            key: "noticeNo",
            title: "通知单号",
            minWidth: 200,
            align: "center",
            show: true,
            config: { type: "text" },
          },
          {
            key: "batchNo",
            title: "批次号",
            minWidth: 200,
            align: "center",
            show: true,
            config: { type: "text" },
          },
          {
            key: "totalCapacity",
            title: "计划产量",
            minWidth: 200,
            align: "center",
            show: true,
            config: { type: "number" },
          },
          {
            key: "remark",
            title: "备注",
            minWidth: 200,
            align: "center",
            show: true,
            config: { type: "textarea" },
          },
        ],
        rules: {
          noticeNo: [
            { required: true, message: "请输入通知单号", trigger: "blur" },
          ],
          batchNo: [
            { required: true, message: "请输入批次号", trigger: "blur" },
          ],
          totalCapacity: [
            {
              required: true,
              message: "请输入计划产量",
              trigger: "blur",
              type: "number",
            },
          ],
        },
      };
    },
  },
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      if (process.env.NODE_ENV === "development") {
        this.init();
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {
      this.leftLoadPage();
      this.getProduct();
    },
    /**
     * @returns
     * 获取左侧表格数据
     */
    leftLoadPage() {
      let data = {
        type: "workunit",
        ...this.leftFilter,
      };

      let fileStr = this._$setFilteStr(data);
      let newFilter = {
        condition: fileStr,
      };

      this.$api.TwinsInstance.query(newFilter).then((res) => {
        this.dataSet.leftTableData = _.sortBy(
          res.map((d) => {
            return {
              id: d.id,
              parentId: "root",
              name: d.comments,
              sf_name: d.values.name,
              sf_code: d.values.workCenterId,
              hier: {
                ...d.hier,
              },
            };
          }),
          ["name"]
        );
        console.log(this.dataSet.leftTableData);
        if (this.dataSet.leftTableIds.length > 0) {
          this.rightLoadPage(this.dataSet.leftTableIds);
        }
      });
    },
    /**
     * @returns
     * 获取右侧表格数据
     */
    rightLoadPage(ids) {
      this._$queryByIds(this.models.workNotice.clzs, ids).then((flag) => {
        if (flag) {
          this.dataSet.rightTableData =
            this.models.workNotice.clzs.valueRecords;
        }
      });
    },
    /**
     * 获取投料数据
     * @param {页面配置} pageNavigation 
     * @param {筛选条件} filter 
     */
    feedLoadPage(pageNavigation, filter) {
      this.vms.feedTable.loading = true;
      filter = this._merge(filter, {
        className: this.models.tank.className,
        type: this.models.tank.type,
        
      });
      let data = {
        pageNumber: pageNavigation.pageNumber,
        pageSize: pageNavigation.pageSize,
        condition: this._$setFilteStr(filter),
        workCenterId: this.feedWorkCenterId,
      };
      this.$api.production.queryTankNotLinkByPage(data).then((res) => {
        this.vms.feedTable.loading = false;
        let tableData = this._clone(res.records);

        this.dataSet.feedTableData = tableData.map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
        this.vms.feedTable.pageNavigation.total = res.recordCount;
      });
    },
    // 开工
    startWork(row) {
      if (row.status != "创建") {
        this.$Message.error("请选择创建状态的数据");
        return;
      }
      this.$api.workCenter.startWorkNotice(row).then((res) => {
        this.$Message.success("操作成功");
        this.rightLoadPage(this.dataSet.leftTableIds);
      });
    },
    // 完工（暂时不用）
    // endWork(row) {
    //   if (row.status != "开工") {
    //     this.$Message.error("请选择开工状态的数据");
    //     return;
    //   }
    //   this.$api.workCenter.endWorkNotice(row).then((res) => {
    //     this.$Message.success("操作成功");
    //     this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
    //   });
    // },

    /**
     *
     * @param {当前数据} row
     * @param {索引} index
     */
    leftClick(row, index) {
      if (row.hier.content && row.hier.content.length > 0) {
        this.dataSet.leftTableIds = row.hier.content.map(
          (item) => item.link.linkId
        );
        this.rightLoadPage(this.dataSet.leftTableIds);
      } else {
        this.dataSet.rightTableData = [];
        this.$Message.info("没有初始数据，请检查");
      }
    },

    /**
     * 编辑计划
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    rightTableEdit(row, index) {
      this._modalShow("editModal");
      this.dataSet.rightFormData = row;
    },
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        if (valid) {
          this.models.workNotice.clz.setRecord(this.dataSet.rightFormData);
          this.models.workNotice.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              btn.loading = false;
              this.rightLoadPage(this.dataSet.leftTableIds);
            }
          });
        }
        btn.loading = false;
      });
    },
    // 绑定投料数据
    feedBindLoadTable() {
      this.dataSet.feedIds = this.dataSet.feedTableSelection.map((item) => {
        return item.link.linkId;
      });
      if (this.dataSet.feedIds.length == 0) {
        this.dataSet.feedTableBindData = [];
        return;
      }
      this._$queryByIds(this.models.tank.clzs, this.dataSet.feedIds).then(
        (res) => {
          let tableData = this._clone(this.models.tank.clzs.records);
          tableData.forEach((item, index) => {
            item._checked = true;
          });
          this.dataSet.feedTableBindData = tableData.map((item) => {
            return {
              ...item,
              ...item.values,
            };
          });
          this.vms.feedTable.pageNavigation.total = res.recordCount;
        }
      );
    },
    /**
     * 选择投料
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    handleFeed(row, index) {
      console.log(row);
      this.vms.feedModal.show = true;
      this.dataSet.feedCurrentIndex = index;
      this.dataSet.feedTableCurrent = row;
      this.feedWorkCenterId = row.workCenterId;
      // this.dataSet.feedTableCurrent =  this.dataSet.rightTableData[this.dataSet.feedCurrentIndex]
      this.parentId = this._$getHierItemField(
        this.dataSet.feedTableCurrent.hier,
        "records",
        "nodeId"
      );
      this.dataSet.feedTableSelection =
        this.dataSet.feedTableCurrent.hier.content.filter(
          (item) => item.parentId == this.parentId
        );
      this.dataSet.feedIds = this.dataSet.feedTableSelection.map(
        (row) => row.link.linkId
      );
      this.vms.feedTable.pageNavigation.pageNumber = 1;
      this.feedLoadPage(this.vms.feedTable.pageNavigation, {});
    },
    // 绑定投料
    feedTableSelect(selection) {
      let selIds = selection.map((item) => item.id);
      if (this.vms.feedModal.tabName == "未绑定") {
        let dataArray = selIds.map((id) => {
          return {
            containerModel: this.models.workNotice.modelType,
            containerId: this.dataSet.feedTableCurrent.id,
            parentId: this.parentId,
            linkId: id,
            values: { linkId: id },
          };
        });
        this.$api.HierInstanceSaveHier(dataArray).then((flag) => {
          this.feedUpdateData();
        });
      } else {
        let linkIds = this.dataSet.feedTableSelection.map((item) => {
          return item.link.linkId;
        });
        let ids = this._diff(selIds, linkIds);
        let delIdItems = this.dataSet.feedTableSelection.filter((item) =>
          ids.includes(item.link.linkId)
        );
        let delIds = delIdItems.map((item) => item.id);
        this.$api.HierInstanceDeleteHier(delIds).then((flag) => {
          this.feedUpdateData();
        });
      }
    },
    feedModalOk() {
      this.vms.feedModal.show = false;
      this.rightLoadPage(this.dataSet.leftTableIds);
    },
    feedUpdateData() {
      this.models["workNotice"].clz
        .queryById(this.dataSet.feedTableCurrent.id)
        .then((res) => {
          this.dataSet.feedTableCurrent =
            this.models["workNotice"].clz.valueRecord;
          this.dataSet.rightTableData[this.dataSet.feedCurrentIndex] =
            this.models["workNotice"].clz.valueRecord;
          this.dataSet.feedTableSelection =
            this.dataSet.feedTableCurrent.hier.content.filter(
              (item) => item.parentId == this.parentId
            );
          if (this.vms.feedModal.tabName == "未绑定") {
            this.feedLoadPage(this.vms.feedTable.pageNavigation, {});
          } else {
            this.feedBindLoadTable();
          }
        });
    },
    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          console.log(res);
          // this.dataSet.routing = res.data.data.records;
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
